<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 *  费用
 *
 */
class Bill extends Backend
{
    /**
     * Bill模型对象
     * @var \app\admin\model\Bill
     */
    protected $model = null;
    protected $dzd =null;
    protected $quickSearchField = ['BILLID'];

    protected $defaultSortField = 'BILLID,desc';

    protected $preExcludeFields = [''];
    protected $noNeedLogin      = ['*'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\Bill;
        $this->dzd =new \app\admin\model\Dzd();
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $tzid=$this->request->get('tzid');
//        $tzid='LBLADM200600002';
        if(empty($where)){
            $wheres=" tzid='$tzid'";
        }

        $shou = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->where("billtype='0'")
            ->where($wheres)
            ->order($order)
            ->paginate($limit);
        $fu = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where("billtype='1'")
            ->where($wheres)
            ->where($where)
            ->order($order)
            ->paginate($limit);
        $this->success('', ['shou'=>[
            'list'   => $shou->items(),
            'total'  => $shou->total(),
            'remark' => get_route_remark(),
        ],'fu'=>[
            'list'   => $fu->items(),
            'total'  => $fu->total(),
            'remark' => get_route_remark(),
        ]]);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $adminInfo          = $this->auth->getInfo();
            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $data['BILLID']='TD'. $this->microtime_format('YmdHisx',$this->microtime_float());
            $data['OPNAME']=$adminInfo['nickname'];
            $data['OPDATETIME']=date('Y-m-d H:i:s',time());
            $data['OPDEPT']=$adminInfo['department'];

            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }
    /**
     * 自动计算
     */
    public function calculation(){
        $tzid=$this->request->get('tzid');
        $adminInfo          = $this->auth->getInfo();
        $query= Db::query("select * from bill where tzid='$tzid' and autoadd='1'");
        if($query){
            $this->error('已存在自动计算费用，不能重复生成！');
        }
        $sql="SET NOCOUNT ON ; EXEC createautobill '".$tzid."',' $adminInfo[id]'";
        $q= Db::query("$sql");
        if($q){
            $this->success('成功');
        }else{
            $this->error('失败');
        }
    }
    /**
     * 取消自动计算
     */
    public function cancel(){
        $tzid=$this->request->get('tzid');

        $query= Db::query("delete bill where tzid='$tzid' and autoadd='1' and checked='0'");
        $this->success('',$query);

    }
    /**
     * 删除
     * @param array $ids
     */
    public function del(array $ids = [])
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(__('Parameter error'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
        }

        $pk    = $this->model->getPk();
        $data  = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($data as $v) {
                $count += $v->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }
    /**
     * 提交/取消审核
     */
    public function tj(){
        $get=$this->request->get();

        $adminInfo          = $this->auth->getInfo();
        if($get['type']==1){
            $save=['TJFLAG'=>1,'TJOP'=>$adminInfo['nickname'],'TJDATETIME'=>date('Y-m-d H:i:s',time())];
        }else{
            $save=['TJFLAG'=>0,'TJOP'=>null,'TJDATETIME'=>null];
        }
        $res=$this->model->where('TZID',$get['tzid'])->save($save);
        if($res){
            $this->success('成功');
        }else{
            $this->error('失败');
        }
    }
    /**
     * 审核/取消
     *
     * types 通过还是全部取消审核
     */
    public function examine(){
        $get=$this->request->get();

        $adminInfo          = $this->auth->getInfo();
        if($get['types']==1){
            $up=['CHECKED'=>1,'CHECKER'=>$adminInfo['nickname'],'CHECKDATETIME'=>date('Y-m-d H:i:s',time())];
        }else{
            $no=$this->model->where('TZID',$get['TZID'])->where("invoiceid!='*'")->select();
            if($no){
                $this->error('不能取消审核');
            }
            $up=['CHECKED'=>0,'CHECKER'=>'','CHECKDATETIME'=>''];
        }
       $save= $this->model->where(['TZID'=>$get['TZID']])->save($up);
        if($save){
            $this->success('操作成功');
        }else{
            $this->error('操作失败');
        }
    }
    public function index_dz(){
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $adminInfo          = $this->auth->getInfo();
        $get=$this->request->get();
//        $get=['type'=>1,'TZID'=>'2103SHLBL0001'];
        if($get['type']==1){
            $wheres='BILL.BILLTYPE=0';
        }else{
            $wheres='BILL.BILLTYPE=1';
        }

        $res = $this->model
            ->field("BILL.BILLID,BILL.MARKNO,
	BILL.JOBNO,
	BILL.CORPCODE,
	BILL.ITEMCODE,
	BILL.MONEYTYPE,
	BILL.MONEY,
	BILL.TAXRATE,
	BILL.AMOUNT,
	BILL.PRICETYPE,
	BILL.RATIO,
	(SELECT DZOP FROM dzd WHERE dzd.DZDNO=BILL.MARKNO) AS DZOP,
	(SELECT DZDATE FROM dzd WHERE dzd.DZDNO=BILL.MARKNO) AS DZDATE,
	(SELECT JOBOP FROM dzd WHERE dzd.DZDNO=BILL.MARKNO) AS JOBOP,
	(SELECT JOBDATE FROM dzd WHERE dzd.DZDNO=BILL.MARKNO) AS JOBDATE")
            ->join('codelib CODELIB','BILL.ITEMCODE=CODELIB.CODE')
            ->alias('BILL')
            ->where($wheres)
            ->where($where)
            ->where('BILL.TZID','in',$get['TZID'])
            ->where("CODELIB.CODETYPE='itemcode'")
            ->order($order)
//            ->fetchSql()->select();
            ->paginate($limit);
//        var_dump($res);die;
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 加入对账单
     */
    public function add_dz()
    {
        $get=$this->request->get();
        $up=$this->model->where('BILLID','in',$get['BILLID'])->save(['MARKNO'=>$get['MARKNO']]);
        if($up){
            $this->success('加入成功');
        }else{
            $this->error('加入失败');
        }
    }
    public function dele_xy(){
        $get=$this->request->get();
        //先效验bill是不是同一对账单号
//        $get['BILLID']=['YS20210324151908'];
//        $get['type']=0;
//        var_dump($get);die;
        $MARKNO=$this->model->where('BILLID','in',$get['BILLID'])->group('MARKNO')->column('MARKNO');
        if(empty($MARKNO[0])){
            $this->error('请选择已经生成对账单的数据');
        }
        if(count($MARKNO)>1){
            $this->error('请选择同一对账单的数据');
        }
        //效验发票申请或审核
        $status=$this->dzd->where('DZDNO',$MARKNO[0])->find();

        if($get['type']==0){
            if($status['FPSQ']==1){
                $this->error('做过发票申请不允许删除。');
            }
        }else{
            if($status['CHECKED']==1){
                $this->error('应付已审核不允许删除');
            }
        }
        if($status['JOBNO']!=''){
            $this->error('JOBNO存在不允许删除');
        }
        $cout=$this->model->where('MARKNO',$MARKNO[0])->count();
        $b_c=count($get['BILLID']);
        if($cout>$b_c){
            $this->success("当前有 $b_c 票费用明细即将从应收账单号$MARKNO[0]中删除，确认是否删除？",1);
        }else{
            $this->success("当前有 $b_c 票费用明细即将从应收账单号$MARKNO[0]中删除，删除后对账单号$MARKNO[0]下已费用据，也将被一起删除，确认是否删除？",2);

        }
    }
    public function dele_dz(){
        $get=$this->request->get();
        $MARKNO=$this->model->where('BILLID','in',$get['BILLID'])->value('MARKNO');
        $del=false;
        $del=$this->model->where('BILLID','in',$get['BILLID'])->save(['MARKNO'=>'']);

        //把dzd表数据也删除
        if($get['type']==2){
            $del= $this->dzd->where('DZDNO',$MARKNO)->del();
        }
        if($del){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }
}